/*
 * Author: Anand Gorantala
 * This is the thread for the upload service. It is created when the peer launches. Whenever a download request comes from
 * other peers, it spawns a new thread to handle the upload
 */
package gmu.swe.project.peer;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Observable;
import java.util.Observer;


public class UploaderService extends Observable implements Observer, Runnable {
	
	ServerSocket uploadSocket = null;
    boolean listening = true;
    int uploadPort;
    int noOfUploads = 0;
    String sharedDirectory= "";
    UploaderThread uploader;
	
    public UploaderService(int port, String sharedDirectory){
    	this.uploadPort = port;
    	this.sharedDirectory = sharedDirectory;
    	System.out.println("Starting the Upload Service on port "+port);
    	
    	Thread thread = new Thread(this);
    	thread.start();
	}
    
    public int UploadsCount(){    	
    	return noOfUploads;
    }
    public void run() {
        try {
            uploadSocket = new ServerSocket(uploadPort);
        } catch (IOException e) {
            System.err.println("Could not listen on port:"+uploadPort);
            System.exit(-1);
        }

		try {
	        while (listening) {
				uploader = new UploaderThread(uploadSocket.accept(), sharedDirectory);
				uploader.addObserver(this);
				noOfUploads++;
				stateChanged();
	        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    public void stateChanged() {
    	setChanged();
    	notifyObservers();
    }
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		noOfUploads--;
		stateChanged();
	}
}
